#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flask应用工厂
创建和配置Flask应用实例
"""

from flask import Flask
from flask_cors import CORS
import json
from datetime import datetime

from config import current_config
from database.mysql_manager import mysql_manager
from controllers.auth_controller import auth_bp
from controllers.project_controller import project_bp
from test_data_api import test_data_bp
from middleware.error_handlers import register_error_handlers
from middleware.request_middleware import before_request, after_request
from utils.response_helper import success_response


class JSONEncoder(json.JSONEncoder):
    """自定义JSON编码器"""
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()
        return json.JSONEncoder.default(self, o)


def create_app(config=None):
    """
    应用工厂函数
    
    Args:
        config: 配置对象，默认使用current_config
        
    Returns:
        Flask应用实例
    """
    app = Flask(__name__)
    
    # 使用传入的配置或默认配置
    if config is None:
        config = current_config
    
    # 配置应用
    configure_app(app, config)
    
    # 初始化扩展
    initialize_extensions(app, config)
    
    # 注册蓝图
    register_blueprints(app)
    
    # 注册中间件
    register_middleware(app)
    
    # 注册错误处理器
    register_error_handlers(app)
    
    # 注册基础路由
    register_basic_routes(app)
    
    return app


def configure_app(app, config):
    """配置应用"""
    # 设置JSON序列化器
    app.json.encoder = JSONEncoder
    
    # 基础配置
    app.config['DEBUG'] = config.DEBUG
    app.config['SECRET_KEY'] = getattr(config, 'SECRET_KEY', 'dev-secret-key')
    
    # 数据库配置
    app.config['SQLALCHEMY_DATABASE_URI'] = config.MYSQL_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = config.SQLALCHEMY_TRACK_MODIFICATIONS
    app.config['SQLALCHEMY_ECHO'] = config.SQLALCHEMY_ECHO


def initialize_extensions(app, config):
    """初始化扩展"""
    # 配置CORS
    CORS(app, origins=config.CORS_ORIGINS, supports_credentials=True)
    
    # 初始化数据库连接
    mysql_manager.init_app(app, config.MYSQL_URI)


def register_blueprints(app):
    """注册蓝图"""
    app.register_blueprint(auth_bp)
    app.register_blueprint(project_bp)
    app.register_blueprint(test_data_bp)


def register_middleware(app):
    """注册中间件"""
    app.before_request(before_request)
    app.after_request(after_request)


def register_basic_routes(app):
    """注册基础路由"""
    
    @app.route('/')
    def index():
        """根路径"""
        return success_response(
            data={'message': f'Welcome to {current_config.APP_NAME}'},
            message='API is running'
        )
    
    @app.route('/api/health')
    def health_check():
        """健康检查"""
        # 检查数据库连接
        db_status = mysql_manager.health_check()
        
        return success_response(
            data={
                'status': 'healthy',
                'version': current_config.APP_VERSION,
                'database': db_status,
                'gray_mode': current_config.GRAY_MODE
            },
            message='Service is healthy'
        )
    
    @app.route('/api/config')
    def get_config():
        """获取配置信息（仅公开信息）"""
        return success_response(
            data={
                'app_name': current_config.APP_NAME,
                'version': current_config.APP_VERSION,
                'gray_mode': current_config.GRAY_MODE,
                'debug': current_config.DEBUG
            },
            message='Configuration retrieved'
        )